// 数据集
import React, { RefObject } from 'react';
import { connect } from 'react-redux';
import styles from './index.module.scss';
import { Button, Col, Row, Input, Table, Space, Tooltip, /* Typography, */ Popconfirm, message } from 'antd';

import { SearchOutlined, DeleteOutlined, FundViewOutlined, FontSizeOutlined, PieChartOutlined, FileFilled, PlusCircleOutlined } from '@ant-design/icons';

import { dataSetGetFiles, getDataSetPage, dataSetDelete } from 'src/services/DataManage';
import { CreateDataSet } from './components/CreateDataSet';
import { CreateFolder } from './components/CreateFolder';
import TreeNode from 'src/pages/AnalyseManage/PredefinedReport/components/TreeNode';
import NewReportModal from 'src/pages/AnalyseManage/Components/NewReportModal';
import { encryptParam } from 'src/libs/paramsEncrypt';

interface listItemType {
	id: string;
	code: string;
	tableName: string;
	tableDesc: string;
	lastExecuteDate: string;
	modelName: any;
	isFile:any
}

interface IProps {
	record: listItemType;
	handleRename: ( item: listItemType ) => void;
	handleView: ( item: listItemType ) => void;
	createDashboard: ( item: listItemType ) => void;
	handleUpdateFolder: any
	handleDelete:any
	btnAuth:any
}

//	操作栏组件
const OperateComponent = React.memo( ( props: IProps ) => {
	return props.btnAuth.includes( 'bi_dataSet_action' ) ? (
		<Space size="middle">
			{
				props.record.isFile === '0'
					? (
						<>
							<Tooltip placement="topRight" title="重命名">
								<Button
									type="text" icon={ <FontSizeOutlined className={ styles.greenBtn }/> }
									onClick={ () => props.handleRename( props.record ) }>
								</Button>
							</Tooltip>
							<Tooltip placement="topRight" title="查看数据">
								<Button
									type="text" icon={ <FundViewOutlined className={ styles.greenBtn } /> }
									onClick={ () => props.handleView( props.record ) }>
								</Button>
							</Tooltip>
							<Tooltip placement="topRight" title="新建仪表板">
								<Button type="text" icon={ <PieChartOutlined className={ styles.greenBtn } /> }
									onClick={ () => props.createDashboard( props.record ) }>
								</Button>
							</Tooltip>
							<Tooltip placement="topRight" title="删除">
								<Popconfirm
									okText="确定" cancelText="取消" title="确定删除这一项？" placement="bottom"
									onConfirm={ () => props.handleDelete( props.record ) }>
									<Button type="text" icon={ <DeleteOutlined className={ styles.greenBtn }/> }>
									</Button>
								</Popconfirm>
							</Tooltip>
						</>
					)
					:(
						<>
							<Tooltip placement="topRight" title="重命名">
								<Button
									type="text" icon={ <FontSizeOutlined className={ styles.greenBtn }/> }
									onClick={() => props.handleUpdateFolder( true )}>
								</Button>
							</Tooltip>
							<Tooltip placement="topRight" title="删除">
								<Popconfirm
									okText="确定" cancelText="取消" title="确定删除这一项？" placement="bottom"
									onConfirm={ () => props.handleDelete( props.record ) }>
									<Button type="text" icon={ <DeleteOutlined className={ styles.greenBtn }/> }>
									</Button>
								</Popconfirm>
							</Tooltip>
						</>
					)
			}
		</Space>
	) : (
		<Space size="middle">
			{
				props.record.isFile === '0' && (
					<Tooltip placement="topRight" title="查看数据">
						<Button
							type="text" icon={ <FundViewOutlined className={ styles.greenBtn } /> }
							onClick={ () => props.handleView( props.record ) }>
						</Button>
					</Tooltip>
				)
			}
		</Space>
	);
} );
OperateComponent.displayName = 'OperateComponent';

class DataSet extends React.Component<any,any> {
	//	声明当前页面变量
	state = {
		pageSize: 10,
		page: 1,
		dataList: [],
		total: 0,
		tableLoading: false,
		modalVisible: false, //创建数据集弹窗
		createFolderVisible: false, //新建文件夹弹窗
		reportVisible: false, //新建仪表板弹窗
		editId: '',
		curRow: {}, //当前行数据
		treeData: [],
		currentFolder: '', //当前文件夹id
		selectedCodes: [], //默认选中tree
		folderData: {
			tableName: '',
			tableDesc: ''
		}, //当前文件夹数据
		isUpdateFile: false,
		keyWord: '',
	};

	//	列表表头配置
	columns = [
		{
			title: '表名称',
			dataIndex: 'tableDesc',
			width: 150,
			render: ( text,record ) => {
				let icon;
				if ( record.type === '0' ) {
					icon = ( <span className={ 'iconfont bdhlianjie' } style={ { color: '#86bc25', marginRight: '8px' } }></span> );
				} else if ( record.type === '1' ) {
					icon = ( <span className={ 'iconfont bdhshuchu' } style={ { color: '#86bc25', marginRight: '8px' } }></span> );
				} else {
					icon = ( <FileFilled style={ { color: '#86bc25', marginRight: '8px' } } /> );
				}
				return ( <>
					{
						record.isFile === '1' ? ( 
							<React.Fragment>
								<span className={ 'iconfont bdhwenjianjiadakai' } style={ { marginRight: '8px' } }></span>
								{text}
							</React.Fragment>
						) : (
							<span className="bdh-link" onClick={() => this.handleView( record )} style={ { paddingLeft: '24px' } } >
								{icon}{text}
							</span>
						)
					}
				</> );
			}
		},
		{
			title: '描述',
			dataIndex: 'comments',
			width: 150,
		},
		{
			title: '刷新时间',
			dataIndex: 'lastExecuteDate',
			width: 150,
		},
		{
			title: '所属数据类型',
			dataIndex: 'modelName',
			width: 100,
		},
		{
			title: '操作',
			key: 'action',
			width: 200,
			fixed: 'right' as 'right', // typescript报错
			// eslint-disable-next-line react/display-name
			render: ( record ) => (
				<OperateComponent
					record={ record }
					handleRename={ this.handleRename }
					handleView={ this.handleView }
					createDashboard={ this.createDashboard }
					handleUpdateFolder={ this.hanleCreateFolder }
					handleDelete={ this.handleDelete }
					btnAuth={ this.props.btnAuth }
				></OperateComponent>
			)

		},
	];

	modalRef: RefObject<any> = React.createRef();

	//	声明当前页面方法
	setPageSize = ( size: number ) => {
		this.setState( {
			pageSize: size
		} );
	};

	//	新增/编辑
	handleCreate = () => {
		this.getList();
	};

	// 翻页
	handlePageChange = ( pageNumber: number ) => {
		this.setState( {
			page: pageNumber
		}, () => {
			this.getList();
		} );
	}

	//	打开新建数据集组件
	toggleModal = ( isShow: boolean ) => {
		this.setState( {
			modalVisible: isShow
		} );

		if ( !isShow ) {
			this.setState( {
				curRow: {}
			} );
		}
	};

	// 打开新建文件夹组件
	modalVisible = ( isShow: boolean ) => {
		this.setState( {
			createFolderVisible: isShow
		} );
	};

	//	删除
	handleDelete = async ( item: listItemType ) => {
		const info = await dataSetDelete( item.code );
		if ( info.data.success ) {
			message.success( '删除成功' );
			this.getList();
			if( item.isFile === '1' ) {
				this.getModelFiles();
			}
		}
	};

	//	搜索
	handleSearch = ( e ) => {
		// this.getList();
	};

	// 搜索框输入
	handleSearchChange = ( e ) => {
		this.setState( { keyWord: e.target.value } );
	};

	// 重命名
	handleRename = ( item: listItemType ) => {
		this.setState( {
			modalVisible: true,
			curRow: item,
		} );
	}
		
	// 查看数据
	handleView = ( item: listItemType ) => {
		this.props.history.push( { 
			pathname: `/dataManage/dataSetView/${item.id}`, 
			state: item,
		} );
	}

	// 新建仪表板
	createDashboard = ( item: listItemType ) => {
		this.setState( { reportVisible: true } );
	}

	getList = async () => {
		this.setState( {
			tableLoading: true
		} );
		const info = await getDataSetPage( {
			data: {
				fileId: this.state.currentFolder,
				page: this.state.page,
				size: this.state.pageSize,
			}
		} );
		if ( info.data.success ) {
			let data = this.state.page === 1?[ this.state.folderData ,...info.data.data.rows ]:info.data.data.rows;
			// let data = info.data.data.rows;
			this.setState( {
				dataList: data,
				total: info.data.data.total
			} );
		}
		this.setState( {
			tableLoading: false
		} );
	};

	//点击顶层目录
	onExpand = ( expandedKeys, { expanded: bool, node } ) => {
		this.setState( { currentFolder: node.key },() => {this.getList();} );
	};

	//点击node
	clickNode = item => {
		this.setState( {
			folderData: item,
			currentFolder: item.key,
		}, () => {
			this.getList();
		} );
	};

	//获取所有文件树
	getModelFiles = async () => {
		const info = await dataSetGetFiles( { data: '' } );
		if( info.data.success ) {
			this.setState( {
				treeData: info.data.data.map( item => {return { key: item.id,title: item.tableName,...item };} )
			} );
			if ( info.data.data.length ) {
				this.setState( {
					currentFolder: this.props.location.state? this.props.location.state.id :info.data.data[0].id,
					selectedCodes: [ this.props.location.state? this.props.location.state.id:info.data.data[0].id ],
					folderData: this.props.location.state
						? info.data.data.filter( item => item.id === this.props.location.state.id )[0]
						:info.data.data[0]
				},() => {this.getList();} );
			}
		}
	};
	
	// 新建/更新文件夹
	hanleCreateFolder = ( t ) => {
		this.setState( {
			isUpdateFile: t
		},() => {
			setTimeout( () => {
				if( this.state.isUpdateFile ) {
					this.modalRef.current.setFieldsValue( { 
						folderName: this.state.folderData.tableName,
						// comments: this.state.folderData.comments
					} );
				}
			}, 100 );
			this.modalVisible( true );
		} );

	};

	onSuccess = ( id: string ) => {
		this.setState( { reportVisible: false } );
		this.props.history.push( { pathname: `/analyseManage/editReport/${encryptParam( id )}/${encryptParam( 'true' )}/${encryptParam( 'EDIT' )}` } );
	};
	onCancel = () => {
		this.setState( { reportVisible: false } );
	};


	async componentDidMount() {
		this.getModelFiles();
	}

	render() {
		const btnAuth = this.props.btnAuth;
		return (
			<div className={ styles.page } style={{ display: 'flex' }}>
				<div className={styles.wrap}>
					<div className={styles.tree_container}>
						<p>数据集</p>
						<div className={styles.tree_box}>
							{
								this.state.treeData.map( ( item, index: number ) => (
									<TreeNode
										activeNodeId={ this.state.currentFolder } key={ index } id={ item.key }
										label={ item.title }
										handleClick={ () => this.clickNode( item ) }></TreeNode>
								) )
							}
						</div>
					</div>
				</div>
				<div className={ styles.dispatch }>
					<Row justify="space-between">
						<Col span={ 12 } style={ { textAlign: 'left' } }>
							{
								btnAuth.includes( 'bi_dataSet_addFolder' ) && (
									<Button type="primary" icon={ <PlusCircleOutlined /> } 
										onClick={() => this.hanleCreateFolder( false )}>新建文件夹</Button>
								)
							}
							{/* <Button type='primary' onClick={ () => this.toggleModal( true ) }>创建数据集</Button> */}
						</Col>
						<Col xs={ 24 } sm={ 6 } md={ 6 } lg={ 6 } xl={ 6 } style={ { textAlign: 'right' } }>
							<Input placeholder="请输入表名称回车搜索"
								allowClear 
								onChange={ this.handleSearchChange }
								onPressEnter={ this.handleSearch }
								prefix={<SearchOutlined />} />
						</Col>
					</Row>
					<Table
						// rowSelection={ { type: 'checkbox' } }
						scroll={ { x: '100%' } }
						tableLayout='fixed'
						columns={ this.columns }
						dataSource={ this.state.dataList }
						className={ styles.tableMargin }
						bordered={ true }
						rowKey={ ( row: listItemType ) => row.id }
						size='middle'
						rowClassName={ ( row ) => row.isFile === '1' ? 'row-folder' : '' }
						pagination={ {
							showSizeChanger: true,
							pageSize: this.state.pageSize,
							onChange: this.handlePageChange,
							total: this.state.total,
							onShowSizeChange: ( current, size ) => this.setPageSize( size ),
							showTotal: total => `共 ${ total } 条`,
						} }
					/>
				</div>
				
				{/* 创建数据集 */}
				<CreateDataSet
					ref={ this.modalRef }
					data={ this.state.curRow }
					folderId={ this.state.currentFolder }
					treeData={ this.state.treeData }
					modalVisible={ this.state.modalVisible }
					onCreate={ this.handleCreate }
					closeModal={ this.toggleModal }/>

				{/*	新建文件夹*/}
				<CreateFolder 
					ref={ this.modalRef }
					createFolderVisible={this.state.createFolderVisible }
					isUpdate={this.state.isUpdateFile}
					getModelFiles={this.getModelFiles}
					folderData={this.state.folderData}
					modalVisible={this.modalVisible}/>

				{/* 新建仪表板弹窗 */ }
				<NewReportModal
					modalVisible={ this.state.reportVisible }
					pageType={ 'dashboard' }
					name='新建仪表板'
					onSuccess={ ( id ) => this.onSuccess( id ) }
					onCancel={ () => { this.onCancel(); } } />
			</div>
		);
	}
}

//	映射state到当前组件
const mapStateToProps = ( state ) => {
	return {
		btnAuth: state.btnAuth,
	};
};

export default connect( mapStateToProps )( DataSet );
